package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.HoneyLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Enroll;
import com.example.springboot.entity.News;
import com.example.springboot.entity.User;
import com.example.springboot.service.EnrollService;
import com.example.springboot.service.NewsService;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 功能：用户信息增删查改
 * 作者：刘涵茹
 * 日期：2024/2/14 13:51
 */

@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired//通过注解去拿@Service注解中注入容器的函数数据
    NewsService newsService;
    @Autowired
    UserService userService;
    @Autowired
    EnrollService enrollService;

    /**
     * 新增信息 post
     */
    @PostMapping("/add")
    @HoneyLogs(operation = "竞赛信息", type = LogType.ADD)
    public Result add(@RequestBody News news) {
        try {
            User currentUser = TokenUtils.getCurrentUser(); //获取当前登录的用户信息
            news.setAuthorid(currentUser.getId());
            news.setNum(0);
            news.setStartime(news.getContintime().substring(0,19));
            news.setEndtime(news.getContintime().substring(20));
            news.setCreatedtime(DateUtil.now()); //获取当前的时间(格式: yyyy-mm-dd HH:MM:SS) 如果是today则是yyyy-mm-dd
            newsService.save(news);
        }catch (Exception e) {
            if (e instanceof DuplicateKeyException) {//数据库插入重复错误时报错
                return Result.error("竞赛标题重复");
            } else {
                return Result.error("系统错误");//其他报错
            }
        }
        return Result.success();
    }

    /**
     * 修改信息 put
     */
    @PutMapping("/update")
    @HoneyLogs(operation = "竞赛信息", type = LogType.UPDATE)
    public Result update(@RequestBody News news) {
        try {
            news.setStartime(news.getContintime().substring(0,19));
            news.setEndtime(news.getContintime().substring(20));
            if (!news.getNum().equals(0)){
                return Result.error("已有学生报名,不能修改竞赛信息!");
            }
            newsService.updateById(news);//service中的函数
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {//数据库插入重复错误时报错
                return Result.error("插入数据库错误");
            } else {
                return Result.error("系统错误");//其他报错
            }
        }
        return Result.success();
    }

    /**
     * 单个删除信息 delete
     */
    @HoneyLogs(operation = "竞赛信息", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")//delete需要通过path相关注解使用
    public Result delete(@PathVariable Integer id) {
        News news = newsService.getById(id);
        if (news.getNum().equals(0)){
            newsService.removeById(id);//service中的函数
            return Result.success();
        }else {
            return Result.error("当前竞赛已有人报名,不能删除!");
        }
    }

    /**
     * 批量删除信息 delete
     */
    @HoneyLogs(operation = "竞赛信息", type = LogType.BATCH_DELETE)
    @DeleteMapping("/delete/batch")//delete需要通过path相关注解使用
    public Result batchDelete(@RequestBody List<Integer> ids) {//得到数组，并传到service中
        List<News> newsList = newsService.listByIds(ids);
        List<Integer> numList = newsList.stream().map(News::getNum).distinct().collect(Collectors.toList());
        for (Integer num : numList){
            if (!num.equals(0)){
                return Result.error("竞赛中已有人报名,不能删除!");
            }
        }
        newsService.removeBatchByIds(ids);//service中的函数
        return Result.success();
    }

    /**
     * 查询全部的信息
     */
    @GetMapping("/selectAll")
    public Result selectAll() {//得到数组，并传到service中
        List<News> userList = newsService.list(new QueryWrapper<News>().orderByDesc("id"));
        //service中的函数
        //select * from news order by id desc
        return Result.success(userList);
    }

    /**
     * 单个条件查询
     * 根据id查询单个的信息
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {//得到数组，并传到service中
        News news = newsService.getById(id);//service中的函数
        User user = userService.getById(news.getAuthorid());
        if (user != null){
            news.setAuthor(user.getUsername());
        }
        return Result.success(news);
    }

    /**
     * 分页多个条件模糊查询
     * 根据title查询单个的信息
     */
    @GetMapping("/selectByPage")
    public Result selectByPage(
            @RequestParam Integer pageNum,//页数或者页码
            @RequestParam Integer pageSize,//当前页总共有多少条数据 这两个都是前端传参过来的
            @RequestParam String title,
            @RequestParam String sign
            ) {//得到数组，并传到service中
        QueryWrapper<News> queryWrapper = new QueryWrapper<News>().orderByDesc("id");//默认倒序,让最新的数据在最上面
        queryWrapper.like(StrUtil.isNotBlank(title), "title", title);
        queryWrapper.like(StrUtil.isNotBlank(sign), "sign", sign);
        Page<News> page = newsService.page(new Page<>(pageNum, pageSize), queryWrapper);//service中的函数
        List<News> records = page.getRecords();
        for (News recode : records){
            Integer authorid = recode.getAuthorid();
            User user = userService.getById(authorid);
            if (user != null){
                recode.setAuthor(user.getUsername());
            }
        }
        return Result.success(page);
    }
}
